<template>
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :minHeight="500"
    :width="580"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <Tabs v-model:activeKey="activeKey" @change="onTabChange">
      <TabPane key="1" :tab="t('routes.demo.workFlow.startFlow.property')">
        <Form :labelCol="{ span: 6 }" :wrapperCol="{ span: 16, offset: 1 }">
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.name')">
            <Input
              v-model:value="lcName"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.namePlaceholder')"
            />
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.code')">
            <Input
              v-model:value="lcCode"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.codePlaceholder')"
              readOnly
            >
              <template #addonAfter>
                <Tooltip
                  :title="t('routes.demo.workFlow.startFlow.propertySet.selectFlowTemplate')"
                >
                  <a-button @click="handleSelectFlow">...</a-button>
                </Tooltip>
              </template>
            </Input>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.startTime')">
            <Input
              v-model:value="lcStarTime"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.startTimePlaceholder')"
              readOnly
            />
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.principal')">
            <Input
              v-model:value="lcCharge"
              :placeholder="t('routes.demo.workFlow.startFlow.propertySet.principalPlaceholder')"
              disabled
            />
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.stepSelect')">
            <Checkbox v-model:checked="lcChecked">{{
              t('routes.demo.workFlow.startFlow.propertySet.allowStepSelect')
            }}</Checkbox>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.backMethod')">
            <RadioGroup v-model:value="lcBack">
              <Radio value="0">{{
                t('routes.demo.workFlow.startFlow.propertySet.backMethodCustom')
              }}</Radio>
              <Radio value="1">{{
                t('routes.demo.workFlow.startFlow.propertySet.backMethodSelect')
              }}</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.overdueTime')">
            <Row>
              <Col :span="8">
                <Input
                  v-model:value="lcDay"
                  :placeholder="
                    t('routes.demo.workFlow.startFlow.propertySet.overdueTimePlaceholder')
                  "
                  :disabled="currentSelectWkf.length === '1'"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.days') }}</span>
              </Col>
              <Col :span="8">
                <Input
                  v-model:value="lcHour"
                  :placeholder="
                    t('routes.demo.workFlow.startFlow.propertySet.overdueTimePlaceholder')
                  "
                  :disabled="currentSelectWkf.length === '1'"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.hours') }}</span>
              </Col>
            </Row>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.propertySet.overdueMessage')">
            <Input
              v-model:value="lcMessage"
              :placeholder="
                t('routes.demo.workFlow.startFlow.propertySet.overdueMessagePlaceholder')
              "
              disabled
            />
          </FormItem>
        </Form>
      </TabPane>
      <TabPane key="2" :tab="t('routes.demo.workFlow.startFlow.step')">
        <BasicTable @register="registerTable" :data-source="stepList" :key="new Date().getTime()" />
        <Form :model="lcbjform" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 1 }">
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.name')">
            <Input
              v-model:value="lcbjform.name"
              :placeholder="t('routes.demo.workFlow.startFlow.stepSet.namePlaceholder')"
              readonly
              :disabled="currentSelectStep.process === 7 && currentSelectStep.isfirst"
            >
              <template #suffix>
                <Icon icon="ion:ios-close-outline" @click="clearName" />
              </template>
              <template #addonAfter>
                <a-button
                  type="primary"
                  @click="handleAdjust"
                  :disabled="currentSelectStep.process === 7 && currentSelectStep.isfirst"
                  >{{ t('routes.demo.workFlow.startFlow.stepSet.adjustStepPrincipal') }}</a-button
                >
              </template>
            </Input>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.overdueTime')">
            <Row>
              <Col :span="8">
                <Input
                  v-model:value="lcbjform.day"
                  :placeholder="t('routes.demo.workFlow.startFlow.stepSet.overdueTimePlaceholder')"
                  :disabled="currentSelectStep.argument === '1'"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.days') }}</span>
              </Col>
              <Col :span="8">
                <Input
                  v-model:value="lcbjform.hour"
                  :placeholder="t('routes.demo.workFlow.startFlow.stepSet.overdueTimePlaceholder')"
                  :disabled="currentSelectStep.argument === '1'"
                />
              </Col>
              <Col :span="4" style="text-align: center">
                <span>{{ t('component.time.hours') }}</span>
              </Col>
            </Row>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.workDescription')">
            <Textarea v-model:value="lcbjform.workDesc" />
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.overdueMessage')">
            <Input v-model:value="lcbjform.expireInfo" readonly>
              <template #addonAfter>
                <a-button type="primary" disabled>{{
                  t('routes.demo.workFlow.startFlow.stepSet.adjustMessageReceiver')
                }}</a-button>
              </template>
            </Input>
          </FormItem>
          <FormItem :label="t('routes.demo.workFlow.startFlow.stepSet.finishMessage')">
            <Input v-model:value="lcbjform.completeInfo" readonly>
              <template #addonAfter>
                <a-button type="primary" disabled>{{
                  t('routes.demo.workFlow.startFlow.stepSet.adjustMessageReceiver')
                }}</a-button>
              </template>
            </Input>
          </FormItem>
        </Form>
      </TabPane>
      <TabPane key="3" :tab="t('routes.demo.workFlow.startFlow.object')">
        <BasicTable @register="registerObjTable" :dataSource="objList" />
      </TabPane>
    </Tabs>
  </BasicModal>
  <!-- 选择流程窗口 -->
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :minHeight="200"
    :width="1000"
    @register="registerSelectFlow"
    @ok="handleSelectionSubmit"
  >
    <BasicTable
      @register="registerSelectionTable"
      :dataSource="wkfList"
      :rowSelection="{
        type: 'radio',
        selectedRowKeys: wkfselectedRowKeys,
        onChange: wkfSelectChange,
      }"
    />
  </BasicModal>
  <!-- 调整步骤负责人窗口 -->
  <BasicModal
    v-bind="$attrs"
    :destroyOnClose="true"
    :minHeight="200"
    :width="500"
    @register="registerAdjust"
    @ok="handleAdjustSubmit"
    @cancel="handleAdjustCancel"
  >
    <InputSearch
      :placeholder="t('routes.demo.workFlow.initiateFlowPage.search')"
      style="width: 200px; margin-bottom: 10px"
      :allowClear="true"
      @change="changeSearch"
      @search="psnSearch"
    />
    <BasicTable @register="registerAdjustTable" :data-source="psnSelectDatat" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import {
    getFlowStepColumns,
    getFlowObjColumns,
    getSelectionColumns,
    getAdjustColumns,
  } from './flowData';
  import Icon from '/@/components/Icon';
  import {
    Tabs,
    TabPane,
    Form,
    FormItem,
    Input,
    Tooltip,
    Checkbox,
    Radio,
    Row,
    Col,
    InputSearch,
  } from 'ant-design-vue';

  import moment from 'moment';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  import {
    checkInFlowApi,
    getCodeNameApi,
    getInfoTipsApi,
    getStepApi,
    getCommonFlowApi,
    getCheckInApi,
    getNewFlowApi,
    getParticipantApi,
    getTemplateList,
    getTemplateListByType,
  } from '/@/api/demo/flow';
  import { getBorrowFlowTemplate } from '/@/api/demo/knowledge';
  import { getFileTypeAndFlowTypeTemplateList } from '/@/api/demo/document';

  const { t } = useI18n();
  const Textarea = Input.TextArea;
  const RadioGroup = Radio.Group;

  const useCommonStore = useUserStore();
  const { createMessage } = useMessage();
  const activeKey = ref('1');
  const lcName = ref<any>('');
  const lcCode = ref('');
  const lcStarTime = ref('');
  const lcCharge = ref('');
  const lcChecked = ref(false);
  const lcBack = ref('0');
  const lcDay = ref('');
  const lcHour = ref('');
  const currentSelectWkf = ref<any>({});
  const lcMessage = ref('');

  const currentSelectStep = ref<any>({});
  const someInfos = ref<any>({
    projectid: '',
    projectName: '',
    taskName: '',
  });
  const currentSelectFile = ref<any>({});
  const wkfList = ref<any>([]);
  const wkfInfos = ref<any>({});
  const wkfselectedRowKeys = ref<any>([]);
  const stepList = ref<any>([]);
  const stepMessage = ref<any>('');
  const personList = ref<any>([]);
  const psnSelectDatat = ref<any>([]);
  const selectedRowKeys = ref<any>([]);
  const objList = ref<any>([]);
  const lcbjform = ref<any>({
    name: '',
    day: '',
    hour: '',
    workdesc: '',
    expireinfo: '',
    completeinfo: '',
  });
  const currentIndex2 = ref<number>(0);
  const stepCharge = ref<any>({});
  const currentIndex3 = ref('');
  const formsId = ref<any>('');
  const submitType = ref<any>('');

  const [registerModal, { closeModal: closeFlowModal, openModal: openFlowModal }] = useModal();
  const [registerSelectFlow, { openModal: openSelectFlowModal }] = useModal();
  const [registerAdjust, { openModal: openAdjustModal }] = useModal();

  // 步骤表格
  const [registerTable] = useTable({
    columns: getFlowStepColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    canResize: false,
    customRow: (record, index) => {
      return {
        onClick: () => {
          // 打开调整弹窗
          currentSelectStep.value = record;
          if (index === 0) {
            currentSelectStep.value.isfirst = true;
          } else {
            currentSelectStep.value.isfirst = false;
          }
          lcbjform.value.name = currentSelectStep.value.actor;
          lcbjform.value.workdesc = currentSelectStep.value.description;
          currentIndex2.value = index;
        },
      };
    },
    //改变 当负责人代号为空的那一行字体颜色为红色，负责人代号不为空字体颜色为黑色，选中当前行背景色改为蓝色
    rowClassName: (record: any, index) => {
      let classStr = '';
      let actor = record.actor.replace(/\s*/, '');
      if (!actor) {
        if (record.unSelected == '1') {
          classStr += 'rowClassSelected';
        } else {
          classStr += 'rowClass2';
        }
      }
      if (index === currentIndex2.value) {
        classStr += ' rowClass';
      }
      return classStr;
    },
  });

  // 对象表格
  const [registerObjTable] = useTable({
    columns: getFlowObjColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    pagination: false,
    rowKey: 'id',
  });

  // 选择流程表格选中事件
  const wkfSelectChange = (selectedRowKeys) => {
    wkfselectedRowKeys.value = selectedRowKeys;
    currentSelectWkf.value = wkfList.value.find((o) => o.id === wkfselectedRowKeys.value[0]);
    stepList.value = [];
  };

  async function handleSelectionSubmit() {
    if (wkfselectedRowKeys.value.length === 1) {
      lcCode.value = wkfselectedRowKeys.value[0];
      lcBack.value = currentSelectWkf.value.status.toString();
      if (currentSelectWkf.value.status === 0) {
        lcChecked.value = false;
      } else {
        lcChecked.value = true;
      }
      getInfoTipsApi(lcCode.value).then((res) => {
        if (res === null) {
          lcMessage.value = '';
        } else {
          lcMessage.value = res.msgInceptor;
        }
      });

      // 查询步骤信息
      getStepApi(wkfselectedRowKeys.value[0]).then((res) => {
        if (res.length === 1) {
          return createMessage.error(t('routes.demo.workFlow.initiateFlowPage.noStep'));
        }
        stepList.value = res.liststdto;
        currentSelectStep.value = stepList.value[0];
        stepMessage.value = res.message;
        if (stepMessage.value) {
          createMessage.info(res.message);
        }
        // 流程第一步默认为流程发起人
        if (
          stepList.value[0].actor === null ||
          stepList.value[0].actor === '' ||
          stepList.value[0].actor === undefined ||
          stepList.value[0].actor === ' '
        ) {
          stepList.value[0].actor = '@psn@' + useCommonStore.userInfo?.userId;
        }
        stepList.value.forEach((item) => {
          if (
            item.actor !== null &&
            item.actor !== '' &&
            item.actor !== undefined &&
            item.actor !== ' '
          ) {
            let arr = item.actor.split('@');
            let id = arr[arr.length - 1];
            let obj = personList.value.find((o) => o.id == id);
            if (obj != null) {
              item.name = obj.name;
            }
          }
        });
      });
    }
    openSelectFlowModal(false);
  }

  // 选择流程表格
  const [registerSelectionTable] = useTable({
    columns: getSelectionColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    canResize: false,
    striped: false,
    rowKey: 'id',
  });

  async function handleAdjustSubmit() {
    const newStepList = [...stepList.value];
    if (Object.keys(stepCharge.value).length != 0) {
      let obj = newStepList.find((o) => o.id == currentSelectStep.value.id);
      if (obj != null) {
        obj.actor = '@psn@' + stepCharge.value.id;
        obj.name = stepCharge.value.name;
        lcbjform.value.name = '@psn@' + stepCharge.value.id;
      }
      stepList.value = newStepList;
    }
    handleAdjustCancel();
  }

  async function handleAdjustCancel() {
    stepCharge.value = {};
    psnSelectDatat.value = personList.value;
    openAdjustModal(false);
  }

  const changeSearch = (e) => {
    if (e.type === 'click') {
      psnSelectDatat.value = personList.value;
    }
  };
  // 流程步骤选择负责人搜索
  const psnSearch = (value) => {
    if (!value) {
      return;
    } else {
      const searchList = personList.value;
      const resData = searchList.filter((o) => o.id.includes(value) || o.name.includes(value));
      psnSelectDatat.value = resData;
      //如果只有1条记录自动选择
      if (psnSelectDatat.value.length == 1) {
        stepCharge.value = psnSelectDatat.value[0];
      }
    }
  };

  // 调整步骤负责人表格
  const [registerAdjustTable] = useTable({
    columns: getAdjustColumns(),
    showIndexColumn: false,
    showTableSetting: false,
    bordered: true,
    canResize: false,
    striped: false,
    rowKey: 'id',
    customRow: (record) => {
      return {
        onClick: () => {
          stepCharge.value = record;
          currentIndex3.value = record.id;
        },
      };
    },
    rowClassName: (record: any) => {
      return record.id === currentIndex3.value ? 'clickRowStyle' : '';
    },
  });

  // 获取参与者，负责人
  getParticipantApi().then((res) => {
    personList.value = res;
    psnSelectDatat.value = personList.value;
  });
  getParticipantApi();

  // 选择流程
  const handleSelectFlow = () => {
    openSelectFlowModal(true);
  };

  // 清除步骤负责人
  const clearName = () => {
    const newStepList = [...stepList.value];
    let obj = newStepList.find((item) => item.id == currentSelectStep.value.id);
    if (obj != null) {
      obj.actor = '';
      obj.name = '';
      lcbjform.value.name = '';
    }
    stepList.value = newStepList;
  };

  // 调整步骤负责人
  async function handleAdjust() {
    openAdjustModal(true);
  }

  // 切换Tab
  const onTabChange = (key) => {
    if (key === 2) {
      if (stepList.value.filter((item) => item.actor === ' ').length === 1) {
        let count = 0;
        for (let i = 0; i < stepList.value.length; i++) {
          if (stepList.value[i].actor === ' ') {
            count++;
          }
        }
        currentIndex2.value = count;
        currentSelectStep.value = stepList.value.filter((item) => item.actor === ' ')[0];
        if (currentIndex2.value == 0) {
          currentSelectStep.value.isfirst = true;
        } else {
          currentSelectStep.value.isfirst = false;
        }
        lcbjform.value.name = currentSelectStep.value.actor;
        lcbjform.value.workdesc = currentSelectStep.value.description;
      } else {
        currentIndex2.value = 0;
        currentSelectStep.value = stepList.value[0];
        if (currentIndex2.value == 0) {
          currentSelectStep.value.isfirst = true;
        } else {
          currentSelectStep.value.isfirst = false;
        }
        lcbjform.value.name = currentSelectStep.value.actor;
        lcbjform.value.workdesc = currentSelectStep.value.description;
      }
    }
  };

  // 流程事件
  const lcShow = (record, type, keys, selectedFiles, projectid, projectName, taskName, formId) => {
    submitType.value = type;
    formsId.value = formId;
    someInfos.value.projectid = projectid;
    someInfos.value.projectName = projectName;
    someInfos.value.taskName = taskName;
    // 单条流程
    if (record !== undefined) {
      currentSelectFile.value = record;
      //添加对象数据
      objList.value.push(record);
      // 检入流程
      if (type === 'jr') {
        checkInFlowApi(useCommonStore.userInfo?.userId, record.id).then((res) => {
          wkfList.value = res.listwfd;
          lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
          lcCharge.value = '@psn@' + useCommonStore.userInfo.username;
          //获取代号，名称
          getCodeNameApi(
            '检入',
            currentSelectFile.value.name,
            currentSelectFile.value.version,
          ).then((res) => {
            wkfInfos.value = res;
            lcName.value = res.name;
            openFlowModal();
          });
          //如果返回合适的流程id
          if (res.workflowid) {
            let memoryWorkFlowId = localStorage.getItem('memoryWorkFlowId');
            if (memoryWorkFlowId !== null) {
              if (wkfList.value.find((o) => o.id === memoryWorkFlowId)) {
                lcCode.value = memoryWorkFlowId;
                wkfselectedRowKeys.value.push(memoryWorkFlowId);
                currentSelectWkf.value = wkfList.value.find((o) => o.id === memoryWorkFlowId);
              } else {
                lcCode.value = res.workflowid;
                wkfselectedRowKeys.value.push(res.workflowid);
                currentSelectWkf.value = wkfList.value.find((o) => o.id === res.workflowid);
              }
            } else {
              lcCode.value = res.workflowid;
              wkfselectedRowKeys.value.push(res.workflowid);
              currentSelectWkf.value = wkfList.value.find((o) => o.id === res.workflowid);
            }
            getInfoTipsApi(lcCode.value).then((res) => {
              if (res === null) {
                lcMessage.value = '';
              } else {
                lcMessage.value = res.msgInceptor;
              }
            });
            if (wkfselectedRowKeys.value.length === 1) {
              //获取步骤
              getStepApi(wkfselectedRowKeys.value[0]).then((res) => {
                if (res.length === 1) {
                  return createMessage.error(t('routes.demo.workFlow.initiateFlowPage.noStep'));
                }
                stepList.value = res.liststdto;
                currentSelectStep.value = stepList.value[0];
                stepMessage.value = res.message;
                if (stepMessage.value !== null) {
                  createMessage.info(res.message);
                }
                //流程第一步默认为流程发起人
                if (
                  stepList.value[0].actor === null ||
                  stepList.value[0].actor === '' ||
                  stepList.value[0].actor === undefined ||
                  stepList.value[0].actor === ' '
                ) {
                  stepList.value[0].actor = '@psn@' + useCommonStore.userInfo?.userId;
                  stepList.value[0].name = useCommonStore.userInfo.username;
                }
                stepList.value.forEach((item) => {
                  if (
                    item.actor !== null &&
                    item.actor !== '' &&
                    item.actor !== undefined &&
                    item.actor !== ' '
                  ) {
                    let arr = item.actor.split('@');
                    let id = arr[arr.length - 1];
                    let obj = personList.value.find((o) => o.id == id);
                    if (obj !== null) {
                      item.name = obj.name;
                    }
                  }
                });
              });
            }
          }
        });
      }
      // 通用流程
      if (type === 'ty') {
        getCommonFlowApi('', '').then((res) => {
          wkfList.value = res;
          lcName.value = '通用流程';
          lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
          lcCharge.value = '@psn@' + useCommonStore.userInfo?.userId;
          openFlowModal(true, wkfList.value);
        });
        getCodeNameApi(
          '通用',
          currentSelectFile.value.filename,
          currentSelectFile.value.version,
        ).then((res) => {
          wkfInfos.value = res;
        });
      }
      // 通知流程
      if (type === 'tz') {
        getFileTypeAndFlowTypeTemplateList(record.type, '通知流程').then((res) => {
          wkfList.value = res;
          lcName.value = '通知流程';
          lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
          lcCharge.value = '@psn@' + useCommonStore.userInfo?.userId;
          openFlowModal(true, wkfList.value);
        });
        getCodeNameApi(
          '通知',
          currentSelectFile.value.filename,
          currentSelectFile.value.version,
        ).then((res) => {
          wkfInfos.value = res;
        });
      }
      // 检出流程
      if (type === 'jc') {
        getTemplateList(record.type, '检出流程').then((res) => {
          wkfList.value = res;
          lcName.value = '检出流程';
          lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
          lcCharge.value = '@psn@' + useCommonStore.userInfo?.userId;
          openFlowModal(true, wkfList.value);
        });
        getCodeNameApi(
          '检出',
          currentSelectFile.value.filename,
          currentSelectFile.value.version,
        ).then((res) => {
          wkfInfos.value = res;
        });
      }
      // 借阅流程
      if (type === 'jy') {
        getBorrowFlowTemplate(record.type).then((res) => {
          wkfList.value = res;
          lcName.value = '借阅流程';
          lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
          lcCharge.value = '@psn@' + useCommonStore.userInfo?.userId;
          openFlowModal(true, wkfList.value);
        });
        getCodeNameApi(
          '借阅',
          currentSelectFile.value.filename,
          currentSelectFile.value.version,
        ).then((res) => {
          wkfInfos.value = res;
        });
      }
      // 废止流程
      if (type === 'fz') {
        getTemplateListByType(record.type).then((res) => {
          wkfList.value = res;
          lcName.value = '废止流程';
          lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
          lcCharge.value = '@psn@' + useCommonStore.userInfo?.userId;
          openFlowModal(true, wkfList.value);
        });
        getCodeNameApi(
          '废止',
          currentSelectFile.value.filename,
          currentSelectFile.value.version,
        ).then((res) => {
          wkfInfos.value = res;
        });
      }
    }
    // 批量检入
    else {
      selectedRowKeys.value = keys;
      objList.value = selectedFiles;
      getCheckInApi(useCommonStore.userInfo?.userId, selectedRowKeys.value.toString()).then(
        (res) => {
          wkfList.value = res;
          if (res.length > 0) {
            lcCode.value = res[0].name;
            wkfselectedRowKeys.value.push(res[0].id);
            currentSelectWkf.value = res[0];
            // 获取步骤
            if (wkfselectedRowKeys.value.length === 1) {
              getStepApi(wkfselectedRowKeys.value[0]).then((res) => {
                if (res.length === 1) {
                  return createMessage.error(t('routes.demo.workFlow.initiateFlowPage.noStep'));
                }
                stepList.value = res.liststdto;
                currentSelectStep.value = stepList.value[0];
                stepMessage.value = res.message;
                if (stepMessage.value !== null) {
                  createMessage.info(res.message);
                }
                // 流程第一步默认为流程发起人
                if (
                  stepList.value[0].actor === '' ||
                  stepList.value[0].actor === null ||
                  stepList.value[0].actor === undefined ||
                  stepList.value[0].actor === ' '
                ) {
                  stepList.value[0].actor = '@psn@' + useCommonStore.userInfo?.userId;
                  stepList.value[0].name = useCommonStore.userInfo.username;
                }
                stepList.value.forEach((item) => {
                  if (
                    item.actor !== null &&
                    item.actor !== undefined &&
                    item.actor !== '' &&
                    item.actor !== ' '
                  ) {
                    let arr = item.actor.split('@');
                    let id = arr[arr.length - 1];
                    let obj = personList.value.find((item) => item.id === id);
                    if (obj !== null) {
                      item.name = obj.name;
                    }
                  }
                });
              });
            }
          }
          lcStarTime.value = moment(new Date()).format('YYYY年MM月DD日');
          lcName.value = '检入流程-多对象';
          lcCharge.value = '@psn@' + useCommonStore.userInfo?.userId;
          openFlowModal();
        },
      );
    }
  };

  async function handleSubmit() {
    if (currentSelectStep.value.id !== null) {
      const liststi = [];
      const listpdmr = [];
      if (currentSelectFile.value.id === undefined) {
        // 多对象流程
        selectedRowKeys.value.forEach((item) => {
          let listpdmrdto = { target: '' };
          listpdmrdto.target = item;
          listpdmr.push(listpdmrdto);
        });
      } else {
        if (submitType.value !== 'jy') {
          // 单对象流程
          let listpdmrdto = { target: '', version: '' };
          listpdmrdto.target = currentSelectFile.value.id;
          listpdmrdto.version = currentSelectFile.value.version;
          listpdmr.push(listpdmrdto);
        } else {
          // 单对象流程
          let listpdmrdto = { target: '', version: '' };
          listpdmrdto.target = currentSelectFile.value.id;
          listpdmrdto.version = currentSelectFile.value.version;
          // 表单id
          let formPdm = { target: formsId.value, version: '1' };
          listpdmr.push(formPdm);
          listpdmr.push(listpdmrdto);
        }
      }
      // 查询并列流程
      const binLieList = stepList.value.filter((item) => item.listssdto !== null);

      if (binLieList.length > 0) {
        for (let i = 0; i < binLieList.length; i++) {
          let num = 0;
          for (let j = 0; j < binLieList[i].listssdto.length; j++) {
            let arr = stepList.value.filter(
              (o) => o.actor != ' ' && o.id == binLieList[i].listssdto[j].source,
            );
            if (arr.length > 0) {
              continue;
            } else {
              num++;
            }
          }
          if (num == binLieList[i].listssdto.length) {
            return createMessage.info(t('routes.demo.workFlow.initiateFlowPage.noPrincipal'));
          }
        }
      }
      // 验证整理接口传参数据
      for (let i = 0; i < stepList.value.length; i++) {
        const liststidto = { workflowID: '', actor: '', description: '' };
        liststidto.workflowID = stepList.value[i].id;
        if (
          stepList.value[i].actor === ' ' ||
          stepList.value[i].actor === '' ||
          stepList.value[i].actor === undefined
        ) {
          //未选择负责人
          if (stepList.value[i].unSelected === '0') {
            //未设置流程步骤不选择负责人
            return createMessage.error('步骤：' + stepList.value[i].id + '未指定执行人');
          }
        }
        liststidto.actor = stepList.value[i].actor;
        liststidto.description = stepList.value[i].remark;
        liststi.push(liststidto);
      }

      if (liststi.length > 0 && listpdmr.length > 0) {
        let workflowType = '检入';
        if (wkfInfos.value.name == '通用流程') {
          workflowType = '通用';
        }
        if (wkfInfos.value.name == '借阅流程') {
          workflowType = '借阅';
        }
        if (wkfInfos.value.name.includes('检出流程')) {
          workflowType = '检出';
        }
        const params = {
          workflowType: workflowType,
          workflowInstancesid: wkfInfos.value.id,
          workflowInstancesName: lcName.value,
          actor: useCommonStore.userInfo?.userId,
          workflow: currentSelectWkf.value.id,
          remark: currentSelectWkf.value.remark,
          creator: useCommonStore.userInfo?.userId,
          liststi: liststi,
          listpdmr: listpdmr,
          rebacksetting: lcBack.value,
          projectid: someInfos.value.projectid,
          projectname: someInfos.value.projectName,
          taskname: someInfos.value.taskName,
        };
        getNewFlowApi(params).then(() => {
          createMessage.success(t('routes.demo.workFlow.initiateFlowPage.createSuccess'));
          localStorage.setItem('memoryWorkFlowId', currentSelectWkf.value.id);
          handleCancel();
        });
      } else {
        handleCancel();
      }
    }
  }

  // 取消
  async function handleCancel() {
    closeFlowModal();
    lcName.value = '';
    lcCode.value = '';
    lcStarTime.value = '';
    lcBack.value = '0';
    lcCharge.value = '';
    wkfselectedRowKeys.value = [];
    lcbjform.value.name = '';
    lcbjform.value.workdesc = '';
    currentSelectStep.value = {};
    currentSelectWkf.value = {};
    selectedRowKeys.value = [];
    wkfInfos.value = {};
    objList.value = [];
    stepList.value = [];
    stepMessage.value = '';
    lcChecked.value = false;
  }

  // //暴露lcShow方法
  defineExpose({
    lcShow,
  });
</script>

<style lang="less" scoped>
  ::v-deep(.ant-input-group-addon) {
    background-color: #fff !important;
    border: 0 solid #d9d9d9 !important;
  }

  ::v-deep(.clickRowStyle) {
    background-color: #e6f7ff !important;
  }

  ::v-deep(.rowClassSelected) {
    color: orange !important;
  }

  ::v-deep(.rowClass) {
    background-color: #e6f7ff !important;
  }

  ::v-deep(.rowClass2) {
    color: red !important;
  }
</style>
